package com.tff.gmall.manger.upload;

import com.tff.gmall.manger.controller.TestMain;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

public class ImgeUploadUtil {


    public static String uploadImg(MultipartFile multipartFile) throws IOException, MyException {

        String imgUrl = "http://47.94.204.85";
        //获取tracker的配置文件
        String confPaht = TestMain.class.getResource("/tracker.conf").getPath();
        //对获取到的配置文件路径进行一次解码
        confPaht = java.net.URLDecoder.decode(confPaht, "utf-8");

        ClientGlobal.init(confPaht);

        TrackerClient trackerClient = new TrackerClient();

        //获得trackerServer的示例
        TrackerServer trackerServer = trackerClient.getTrackerServer();
        //获得storageClient实例，这个实例就可以用来上传文件
        StorageClient storageClient = new StorageClient(trackerServer, null);

        byte[] bytes = multipartFile.getBytes();
        String originalFilename = multipartFile.getOriginalFilename();
        String exrName = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);
        System.out.println(exrName);
        String[] paths = storageClient.upload_file(bytes, exrName, null);

        for (String s : paths) {
            imgUrl += "/" + s;
        }
        return imgUrl;
    }
}
